package com.pioneer.app.sms.mobile;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pioneer.app.dev.department.Department;
import com.pioneer.app.dev.department.DepartmentDAO;
import com.pioneer.app.dev.osuser.user.Userlist;
import com.pioneer.app.dev.osuser.user.UserlistDAO;


public class SMSServlet extends HttpServlet {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SMSServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public SMSServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		if (logger.isDebugEnabled()) {
			logger.debug("destroy() - start");
		}

		super.destroy(); // Just puts "destroy" string in log
		// Put your code here

		if (logger.isDebugEnabled()) {
			logger.debug("destroy() - end");
		}
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("doGet(HttpServletRequest, HttpServletResponse) - start");
		}

		InputStream is=request.getInputStream();
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String str=new String("中国||13009998776|*|华北||13900909876");
		String content =getInputStream(request);
		
//		System.out.println("content="+content);
		logger.info("手机端请求内容："+content);
		
		OutputStream bos = new FileOutputStream("d:\\smslog.txt"); 

		bos.write(content.getBytes());
		bos.close();  
		
		
		System.out.println("content="+content);
			StringBuffer bf=new StringBuffer(1024);
//		String command=sb.toString();
//		System.out.println("abc="+command);
		String command=content.substring(0, 5);
		if("GET01".equalsIgnoreCase(command)){
//			取部门信息
			DepartmentDAO dao=new DepartmentDAO();
			List dpts=dao.findByCondition(null);
			if(null!=dpts){
				Iterator it=dpts.iterator();
				Department dpt=null;
				if(it.hasNext()){
					dpt=(Department)it.next();
					bf.append(dpt.getId()).append("||").append(dpt.getName());
				}
				while(it.hasNext()){
					dpt=(Department)it.next();
					bf.append("|*|").append(dpt.getId()).append("||").append(dpt.getName());
				}
			}
		}else if("GET02".equalsIgnoreCase(command)){
//			根据部门取人员信息
			String deptId=content.substring(5, content.length());
			UserlistDAO userdao=new UserlistDAO();
			List users=userdao.findByCondition("departmentId="+deptId);
			if(null!=users){
				Iterator uit=users.iterator();
				Userlist user=null;
				if(uit.hasNext()){
					user=(Userlist)uit.next();
					bf.append(user.getUserName()).append("||").append(user.getTelphone());
				}
				while(uit.hasNext()){
					user=(Userlist)uit.next();
					bf.append("|*|").append(user.getUserName()).append("||").append(user.getTelphone());
				}
			}
		}else if("GET03".equalsIgnoreCase(command)){
			
			try {
				String contentStr=content.substring(5, 205);
				String telphones=content.substring(205, content.length());
				SendService service=new SendService();
				service.setMobile(telphones);
				service.setContent(contentStr);
				String title=null;
				if(contentStr.length()>15){
					title=contentStr.substring(0,15);
				}else{
					title=contentStr;
				}
				service.setTitle(title);
				service.setSMS();
			} catch (RuntimeException e) {
				logger.error("doGet(HttpServletRequest, HttpServletResponse)", e);

				bf.append(false);
			} catch (Exception e) {
//				e.printStackTrace();
				bf.append("false");
				PrintWriter out = response.getWriter();
				System.out.println("send message:"+bf.toString());
				out.println(bf.toString());
				
				out.flush();
				out.close();
			}
			bf.append("true");
			
		}
		PrintWriter out = response.getWriter();
		System.out.println("send message:"+bf.toString());
		out.println(bf.toString());
		
		out.flush();
		out.close();

		if (logger.isDebugEnabled()) {
			logger.debug("doGet(HttpServletRequest, HttpServletResponse) - end");
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - start");
		}

		doGet(request, response);

		if (logger.isDebugEnabled()) {
			logger.debug("doPost(HttpServletRequest, HttpServletResponse) - end");
		}
	}
	
	
	public static String byte2string(byte[] b, int offset, int len) {
		if (logger.isDebugEnabled()) {
			logger.debug("byte2string(byte[], int, int) - start");
		}

		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(b, offset, len);
			DataInputStream inputstream = new DataInputStream(bais);
			String returnString = inputstream.readUTF();
			if (logger.isDebugEnabled()) {
				logger.debug("byte2string(byte[], int, int) - end");
			}
			return returnString;
		} catch (IOException e) {
			logger.error("byte2string(byte[], int, int)", e);

			if (logger.isDebugEnabled()) {
				logger.debug("byte2string(byte[], int, int) - end");
			}
			return null;
		}
	}
	
	
	private String getInputStream(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("getInputStream(HttpServletRequest) - start");
		}

//  InputStream t_is = null;
  InputStream t_body = null;

  try {
      t_body = request.getInputStream();
      
      //读取输入流
      BufferedReader t_bf = new BufferedReader(new InputStreamReader(
              t_body, "utf-8"));

      String t_xmlSt = null;
      String t_line = null;

      while ((t_line = t_bf.readLine()) != null) {
          t_xmlSt += t_line;
      }
      t_xmlSt=t_xmlSt.substring(4,t_xmlSt.length());
      System.out.println("t_xmlSt::"+t_xmlSt);

		if (logger.isDebugEnabled()) {
				logger.debug("getInputStream(HttpServletRequest) - end");
			}
      return t_xmlSt;
      // 解密
      //t_xmlSt = StringUtil.decryptStr(t_xmlSt);

      
  } catch (UnsupportedEncodingException e) {
			logger.error("getInputStream(HttpServletRequest)", e);

      // TODO Auto-generated catch block
      e.printStackTrace();

		if (logger.isDebugEnabled()) {
				logger.debug("getInputStream(HttpServletRequest) - end");
			}
      return null;
  } catch (IOException e) {
			logger.error("getInputStream(HttpServletRequest)", e);

      // TODO Auto-generated catch block
      e.printStackTrace();

		if (logger.isDebugEnabled()) {
				logger.debug("getInputStream(HttpServletRequest) - end");
			}
      return null;
  } finally {
      try {
          if (t_body != null) {
              t_body.close();
          }
      } catch (IOException e1) {
				logger.error("getInputStream(HttpServletRequest)", e1);

          e1.printStackTrace();
      }
  }
}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
